"""
地址：http://www.netbian.com/

"""
import os

#  导入 requests 和 etree 模块
import requests
from lxml import etree

classify = "meinv"
start_page = 1
end_page = 6


# 确保 "wallpaper" 文件夹存在，
folder_path = f"./wallpaper/{classify}"
if not os.path.exists(folder_path):
    os.makedirs(folder_path)


#  循环下载n页的图片
for i in range(start_page-1, end_page):
    url = f"http://www.netbian.com/{classify}/"  # 网站上分类的url地址
    #  第一页的地址和后面页的地址不同，需要分别处理
    if i == 0:
        url = url + "index.htm"
        i += 1
    else:
        url = url + "index_" + str(i + 1) + ".htm"

    #  设置协议头
    headesp = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35'}

    #  发送get请求并获取响应且设置编码
    resp = requests.get(url, headers=headesp)
    resp.encoding = resp.apparent_encoding

    #  将响应内容解析为etree对象
    xp = etree.HTML(resp.text)

    #  获取每页中的图片详情页链接
    img_url = xp.xpath("/html/body/div[@class='wrap clearfix']/div[@id='main']/div[@class='list']/ul/li/a/@href")
    print(img_url)
    for n in img_url:
        #  根据图片详情页链接再次发送get请求并获取图片地址和名称
        resp = requests.get('http://www.netbian.com' + n)
        resp.encoding = resp.apparent_encoding
        xp = etree.HTML(resp.text)
        img_urls = xp.xpath('//div[@class="pic"]/p/a/img/@src')
        img_name = xp.xpath('//div[@class="pic"]/p/a/img/@alt')

        # 下载并保存到目标文件夹
        for u, n in zip(img_urls, img_name):
            print(f'图片名：{n} 地址:{u}')
            img_resp = requests.get(u)
            with open(f'./{folder_path}/{n}.jpg', 'wb') as f:
                f.write(img_resp.content)
